//
//  UpPrintVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/8/30.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "UpPrintVC.h"
#import "UpOpenViewController.h"

@interface UpPrintVC ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIView *cutView;       ///>截取图片的区域
@property (nonatomic, strong) UIButton *backBtn;     ///>返回按钮
@property (nonatomic, strong) UISegmentedControl *segControl;   ///>选择横竖屏按钮
@property (nonatomic, assign) BOOL isH;              ///>是否是横图

@property (nonatomic, strong) UIScrollView *operScrollView; ///>图片的缩放视图
@property (nonatomic, strong) UIImageView *seeImageView;    ///>待切的图
@property (nonatomic, strong) UIButton *saveBtn;            ///>保存按钮
@property (nonatomic, strong) UIImage *image;               ///>待处理的图片

@end

@implementation UpPrintVC

- (instancetype)initWithImage:(UIImage *)image
{
    self = [super init];
    if (self) {
        self.image = image;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    AdjustsScrollViewInsetNever(self, self.operScrollView);
    self.isNavgationBarHidden = YES;
    self.view.backgroundColor = [UIColor c4Color];

    [self.view addSubview:self.operScrollView];
    [self.operScrollView addSubview:self.seeImageView];
    [self.view addSubview:self.cutView];
    
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.segControl];
    [self.view addSubview:self.saveBtn];
    
    [self initAroundBackView];
    
    [self makeConstraints];
    
    [self layoutview];
}

- (void)initAroundBackView {
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectZero];
    view1.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
    [self.view addSubview:view1];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectZero];
    view2.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
    [self.view addSubview:view2];
    
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectZero];
    view3.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
    [self.view addSubview:view3];
    
    UIView *view4 = [[UIView alloc] initWithFrame:CGRectZero];
    view4.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:.7];
    [self.view addSubview:view4];
    
    view1.userInteractionEnabled = NO;
    view2.userInteractionEnabled = NO;
    view3.userInteractionEnabled = NO;
    view4.userInteractionEnabled = NO;
    
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.right.mas_equalTo(_cutView.mas_left);
    }];
    
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.mas_equalTo(0);
        make.left.mas_equalTo(view1.mas_right);
        make.bottom.mas_equalTo(_cutView.mas_top);
    }];
    
    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(view2.mas_bottom);
        make.left.mas_equalTo(_cutView.mas_right);
        make.right.bottom.mas_equalTo(0);
    }];
    
    [view4 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view1.mas_right);
        make.right.mas_equalTo(view3.mas_left);
        make.top.mas_equalTo(_cutView.mas_bottom);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.backBtn.superview bringSubviewToFront:self.backBtn];
    [self.segControl.superview bringSubviewToFront:self.segControl];
    [self.saveBtn.superview bringSubviewToFront:self.saveBtn];
}

- (void)makeConstraints {
    [self.operScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    
    [self.seeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    
    [self.cutView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.centerY.mas_equalTo(self.view.mas_centerY);
    }];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(20);
        make.width.mas_equalTo(44);
        make.height.mas_equalTo(44);
    }];
    
    [self.segControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(64);
        make.width.mas_equalTo(240);
        make.height.mas_equalTo(40);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.bottom.mas_equalTo(-40);
        make.height.mas_equalTo(45);
    }];
    
}

- (void)layoutview {
    CGFloat width;
    CGFloat height;
    if (_isH) {
        width = KSCREENWIDTH - 60;
        height = width * 9 / 16;
    } else {
        width = KSCREENWIDTH * 3 / 5;
        height = width * 16 / 9;
    }
   
    [self.cutView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(height);
    }];
    
    UIImage *image = self.image;
    CGSize imageSize = image.size;
    
    //>展示的image视图
    CGFloat imgWid = width;
    CGFloat imgHei = imageSize.height*width/imageSize.width;
    
    _operScrollView.maximumZoomScale = imageSize.width/imgWid>1?imageSize.width/imgWid:1;
    [_operScrollView setZoomScale:1.0 animated:YES];
    CGFloat x = (KSCREENWIDTH - width) / 2;
    CGFloat y = (KSCREENHEIGHT - height) / 2;
    if (imgHei >= height) {
        _operScrollView.contentOffset = CGPointMake(-x, -(KSCREENHEIGHT-imgHei)/2);
    } else {
        imgHei = height;
        imgWid = imageSize.width * height/imageSize.height;
        _operScrollView.contentOffset = CGPointMake(-(KSCREENWIDTH-imgWid)/2, -y);
    }
    [self.seeImageView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(imgWid);
        make.height.mas_equalTo(imgHei);
    }];

    _operScrollView.contentSize = _seeImageView.frame.size;
    _operScrollView.contentInset = UIEdgeInsetsMake(y, x, y, x);
}

#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return _seeImageView;
}

#pragma mark -Help
- (void)vOrh:(UISegmentedControl *)btn
{
    if (btn.selectedSegmentIndex == 0 && _isH != NO) {
        _isH = NO;
        [self layoutview];
    }
    
    if (btn.selectedSegmentIndex == 1 && _isH != YES) {
        _isH = YES;
        [self layoutview];
    }
}

- (void)saveAction
{
    //获取截图区域坐标
    NSString *cropUrl = [self calCoordinate];
    //裁切图片
    UIImage *cutImage = [self cutImage];

    UpOpenViewController *vc = [[UpOpenViewController alloc] initWithNibName:@"UpOpenViewController" bundle:nil];
    vc.isOpen = self.isOpen;
    vc.isH = self.isH;
    vc.originImage = self.image;
    vc.image = cutImage;
    vc.cropUrl = cropUrl;
    [UIViewController ig_pushViewController:vc animated:YES];
}

//获取截图区域坐标
- (NSString *)calCoordinate {
    CGRect cutRect = _cutView.frame;
    CGFloat x2 = cutRect.origin.x;
    CGFloat y2 = cutRect.origin.y;
    CGFloat w2 = cutRect.size.width;
    CGFloat h2 = cutRect.size.height;
    
    CGRect imageRect = [_operScrollView convertRect:_seeImageView.frame toView:self.view];
    CGFloat x3 = imageRect.origin.x;
    CGFloat y3 = imageRect.origin.y;
    CGFloat w3 = imageRect.size.width;
    CGFloat h3 = imageRect.size.height;

    //作品剪切路径 cropUrl
    UIImage *image = self.image;
    CGSize imageSize = image.size;
    CGFloat imageWidth = imageSize.width;
    CGFloat imageHeight = imageSize.height;

    //左上角点距左侧的x距离
    int crop_x = ((x2 - x3) * imageWidth)/w3;//aXScale * imageWidth
    //左上角点距左侧的y距离
    int crop_y = ((y2 - y3) * imageHeight)/h3;//aYScale * imageheight
    //裁切后图片的宽
    int crop_w = (w2 * imageWidth)/w3;
    //裁切后图片的高
    int crop_h = (h2 * imageHeight)/h3;
    NSLog(@"=========== %@, %@, %@, %@", @(crop_x), @(crop_y), @(crop_w), @(crop_h));
    
    return [NSString stringWithFormat:@"crop,x_%@,y_%@,w_%@,h_%@", @(crop_x), @(crop_y), @(crop_w), @(crop_h)];
}

//裁切图片
- (UIImage *)cutImage {
    float scale = [[UIScreen mainScreen] scale];
    CGRect originRect = _cutView.frame;
    CGFloat x = originRect.origin.x;
    CGFloat y = originRect.origin.y;
    CGFloat width = originRect.size.width;
    CGFloat height = originRect.size.height;
    CGRect rect1 = CGRectMake(x*scale, y*scale, width*scale, height*scale);
    CGSize size = self.view.frame.size;

    UIGraphicsBeginImageContextWithOptions(size, YES, 0);//设置截屏大小
    [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();//全屏截图
    UIGraphicsEndImageContext();
    
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(viewImage.CGImage, rect1);
    UIImage *cutImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    
    return cutImage;
}

#pragma mark - 懒加载
- (UIImageView *)seeImageView {
    if (!_seeImageView) {
        _seeImageView = [[UIImageView alloc] init];
        _seeImageView.image = self.image;
    }
    return _seeImageView;
}

- (UIScrollView *)operScrollView {
    if (!_operScrollView) {
        _operScrollView = [[UIScrollView alloc] init];
        _operScrollView.alwaysBounceVertical = YES;
        _operScrollView.alwaysBounceHorizontal = YES;
        _operScrollView.showsVerticalScrollIndicator = NO;
        _operScrollView.showsHorizontalScrollIndicator = NO;
        _operScrollView.delegate = self;
        _operScrollView.backgroundColor = [UIColor clearColor];
        _operScrollView.minimumZoomScale = 1;
    }
    return _operScrollView;
}

- (UISegmentedControl *)segControl {
    if (!_segControl) {
//        _segControl = [[UISegmentedControl alloc] initWithItems:@[@"竖屏", @"横屏"]];
        _segControl = [[UISegmentedControl alloc] initWithItems:@[NSLocalizedString(@"Vertical screen", nil), NSLocalizedString(@"Horizontal screen", nil)]];
        _segControl.layer.cornerRadius = 20;
        _segControl.layer.masksToBounds = YES;
        _segControl.layer.borderColor = [UIColor c3Color].CGColor;
        _segControl.layer.borderWidth = 1;
        [_segControl setSelectedSegmentIndex:0];
        [_segControl setBackgroundColor:[UIColor c4Color]];
        [_segControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont font14], NSForegroundColorAttributeName:[UIColor appColor]} forState:UIControlStateSelected];
        [_segControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont font14], NSForegroundColorAttributeName:[UIColor c3Color]} forState:UIControlStateNormal];
        [_segControl addTarget:self action:@selector(vOrh:) forControlEvents:UIControlEventValueChanged];
        _segControl.tintColor = [UIColor c3Color];
    }
    return _segControl;
}

- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _saveBtn.layer.cornerRadius = 20;
        _saveBtn.layer.masksToBounds = YES;
        _saveBtn.backgroundColor = [UIColor appColor];
        _saveBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [_saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//        [_saveBtn setTitle:@"下一步" forState:UIControlStateNormal];
        [_saveBtn setTitle:NSLocalizedString(@"Next", nil) forState:UIControlStateNormal];
        [_saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}

- (UIButton *)backBtn {
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn.imageView setContentMode:UIViewContentModeScaleToFill];
        [_backBtn setImage:[UIImage imageNamed:@"B-22-2"] forState:UIControlStateNormal];
        __weak typeof(self) weakSelf = self;
        [_backBtn setTapActionWithBlock:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }];
    }
    return _backBtn;
}

- (UIView *)cutView {
    if (!_cutView) {
        _cutView = [[UIView alloc] init];
        _cutView.backgroundColor = [UIColor clearColor];
        _cutView.layer.borderColor = [UIColor whiteColor].CGColor;
        _cutView.layer.borderWidth = 1;
        _cutView.userInteractionEnabled = NO;
    }
    return _cutView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
